package com.tanhua.dubbo.api;

import com.tanhua.dubbo.api.mongo.CommentApi;
import com.tanhua.model.enums.CommentType;
import com.tanhua.model.mongo.Comment;
import com.tanhua.model.mongo.Movement;
import com.tanhua.model.vo.PageResult;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.FindAndModifyOptions;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.data.mongodb.core.query.UpdateDefinition;

import java.util.ArrayList;
import java.util.List;

@DubboService
public class CommentApiImpl implements CommentApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 通过动态id调用服务分页查询评论列表
     * @param page
     * @param pageSize
     * @param movementId
     * @return
     */
    @Override
    public PageResult<Comment> findByUserId(Long page, Long pageSize, String movementId) {

        List<Comment> commentList = new ArrayList<>();

        Query query = new Query();
        query.addCriteria(Criteria.where("publishId").is(new ObjectId(movementId))
                .and("commentType").is(CommentType.COMMENT.getType()));

        long count = mongoTemplate.count(query, Comment.class);
        long start = (page - 1) * pageSize;

        if(count > start){
            query.skip(start).limit(pageSize.intValue());
            query.with(Sort.by(Sort.Order.desc("created")));
            commentList = mongoTemplate.find(query, Comment.class);
        }

        return new PageResult<>(page,pageSize,count,commentList);
    }

    /**
     * 新增发表评论信息
     * @param com
     */
    @Override
    public Integer add(Comment com) {
        // 补全动态作者信息
        Query query = new Query(Criteria.where("id").is(com.getPublishId()));
        Movement movement = mongoTemplate.findOne(query, Movement.class);
        com.setPublishUserId(movement.getUserId());

        // 设置时间
        com.setCreated(System.currentTimeMillis());

        // 添加评论
        mongoTemplate.insert(com);

        // 更新动态评论数

        Update update = new Update();
        update.inc(getCollName(com.getCommentType()),1);

        FindAndModifyOptions fao = new FindAndModifyOptions();
        fao.returnNew(true);    // 需要返回新值
        movement = mongoTemplate.findAndModify(query, update, fao, Movement.class);

        // 根据评论类型，获取对应的互动数量
        return movement.statisCount(com.getCommentType());
    }

    /**
     * 删除点赞或者喜欢记录
     * @param com
     * @return
     */
    @Override
    public Integer remove(Comment com) {

        // 删除点赞或者喜欢记录
        Query query = new Query(Criteria.where("publishId").is(com.getPublishId())
                .and("commentType").is(com.getCommentType()).and("userId").is(com.getUserId()));
        mongoTemplate.remove(query,Comment.class);

        // 修改动态表中的总数量
        Query movementQuery = new Query(Criteria.where("id").is(com.getPublishId()));
        Update update = new Update();
        // 自减
        update.inc(getCollName(com.getCommentType()),-1);
        FindAndModifyOptions options = new FindAndModifyOptions();
        // 返回更新后的最新值
        options.returnNew(true);
        Movement movement = mongoTemplate.findAndModify(movementQuery, update, options, Movement.class);

        // 获得最新的评论数量，并返回
        return movement.statisCount(com.getCommentType());
    }

    /**
     * 评论点赞
     * @param com
     * @return
     */
    @Override
    public Integer updateAdd(Comment com) {

        Query query = new Query();
        query.addCriteria(Criteria.where("id").is(com.getId()));

        Update update = new Update();
        update.inc("likeCount",1);
        FindAndModifyOptions option = new FindAndModifyOptions();
        option.returnNew(true);
        Comment comment = mongoTemplate.findAndModify(query, update, option, Comment.class);

        return comment.getLikeCount();
    }


    /**
     * 取消评论点赞
     * @param com
     * @return
     */
    @Override
    public Integer updateDel(Comment com) {
        Query query = new Query();
        query.addCriteria(Criteria.where("id").is(com.getId()));

        Update update = new Update();
        update.inc("likeCount",-1);
        FindAndModifyOptions option = new FindAndModifyOptions();
        option.returnNew(true);
        Comment comment = mongoTemplate.findAndModify(query, update, option, Comment.class);

        return comment.getLikeCount();
    }


    /**
     * 通过评论类型，获取要更新的动态表中的列名
     * @param commentType
     * @return
     */
    private String getCollName(int commentType){
        if(CommentType.LIKE.getType() == commentType){
            return "likeCount";
        }else if(CommentType.COMMENT.getType() == commentType){
            return "commentCount";
        }else{
            return "loveCount";
        }
    }
}
